package com.ice.framework.redission.delaytask;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author wangwei
 * @Date 2022/6/17 16:22
 */
@Slf4j
@Component
public class RedisDelayedQueue {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private DelayedQueueConfig delayedQueueConfig;
    /**
     * 添加队列
     *
     * @param t        DTO传输类
     * @param delay    时间数量
     * @param timeUnit 时间单位
     * @param <T>      泛型
     */
    public <T extends DelayTaskBase> void addQueue(T t, long delay, TimeUnit timeUnit, String queueName) {
        log.debug("添加队列{},delay:{},timeUnit:{}" + queueName, delay, timeUnit);
        RBlockingQueue<T> blockingFairQueue = redissonClient.getBlockingQueue(queueName);
        t.setRetryNum(0);
        t.setRetryMaxNum(delayedQueueConfig.getRetryMaxNum());
        t.setQueueName(queueName);
        t.setDelayTime(delay);
        t.setTimeUnit(timeUnit);
        RDelayedQueue<T> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
        delayedQueue.offer(t, delay, timeUnit);
    }
}
